<template lang="">
	<view class="interact-message">
		<u-loadmore
			status="loading"
			v-if="loading"
		/>
		<u-skeleton
			:loading="loading"
			:animate="true"
			rows="5"
		>
			<scroll-view
				v-if="!loading"
				:scroll-top="scrollToTop"
				scroll-with-animation
				scroll-y
				:scroll-into-view="viewIndex"
				:style="{ transform: 'translateY('+translateY+'px)', transition: isDown ? '0s' : 'transform 0.2s','padding-top': '160rpx' }"
				refresher-enabled
				:refresher-triggered="triggered"
				:refresher-threshold="50"
				refresher-background="white"
				@refresherrefresh="refresh"
				@refresherrestore="onRestore"
				@onPullDown="refresh()"
				@onLoadMore="onLoadMore"
			>
				<view
					class="Interact-msgs"
					v-for="item in messageList"
					:key="item"
				>
					<InteractBar
						type="comment"
						:messageList="item"
					/>
				</view>
				<text>没有更多了···</text>
			</scroll-view>
		</u-skeleton>
	</view>
</template>
<script>
import InteractBar from './components/interactBar.vue'
import { getmessageList } from '@/api/ChatApi/chat.js'
import { getUserInfo } from '@/store/user.js'
import { websocetObj } from '@/utils/websocket.js'
let inter

export default {
  components: {
    InteractBar
  },
  data() {
    return {
      bgColor: '#EDEDED',
      // 获取用户的信息
      messageList: [],
      isSocketOpen: '',
      timer: null,
      loading: true,
      triggered: false,
      userList: [],
      inter: null

    }
  },
  onPullDownRefresh() {
    // 监听下拉刷新动作的执行方法，每次手动下拉刷新都会执行一次
    console.log('refresh')
    setTimeout(function() {
      uni.stopPullDownRefresh() // 停止下拉刷新动画
    }, 1000)
  },
  created() {
    this.getMessageList()

    this.inter = setInterval(() => {
      this.getMessageList()
    }, 2000)

    // 在onload的时候调用，创建webscoet连接对象，参数分别为：url、获取后端返回数据、监听websocket的链接失败返回的报错、监听链接状态，返回布尔值
    // websocetObj.sokcet('wss://xwwww.top/skillgo/imMessage/' + getUserInfo().id, this.getWebsocetData, this.getWebsocetError, this.onErrorSucceed)
  },
  /**
	 * 连接websocket实现
	 */
  methods: {
    connectSocket() {
      websocetObj.stop()
      websocetObj.sokcet('wss://xwwww.top/skillgo/imMessage/' + getUserInfo().id, this.getWebsocetData, this.getWebsocetError, this.onErrorSucceed)
    },
    /**
		 *获取消息
		 */
    connectWeb() {

      uni.connectSocket({
        url: 'wss://xwwww.top/skillgo/imMessage/' + getUserInfo().id,
        success: res => {}
      })
      // 监听socket打开
      uni.onSocketOpen((res) => {
        this.isSocketOpen = true

        console.log('WebSocket连接已打开！', res)
      })
      // 监听socket关闭
      uni.onSocketClose(() => {
        this.isSocketOpen = false
        console.log('WebSocket连接已关闭！')
      })
      // 监听socket错误
      uni.onSocketError(() => {
        this.isSocketOpen = false
        console.log('WebSocket连接打开失败')
      })

      uni.onSocketMessage((res) => {
        // let infos=JSON.parse(res.data)  //socket信息是字符串，需要先转成json形式再去解析内容

        if (res.data) { // 判断消息类型是否为用来监听链接的ping，如果是则不继续执行只是控制台显示
          let msgList = res.data

          msgList = msgList.slice(1)

          msgList = msgList.slice(0, msgList.length - 2)

          msgList = msgList.split('},')
          this.messageList = []
          for (let i = 0; i < msgList.length; i++) {
            this.messageList.push(JSON.parse(msgList[ i ] + '}'))
          }
          console.log('res', this.messageList)
        }
      })

    }, /**
		 *获取消息
		 */
    // websocet函数回调：返回监听的数据
    getWebsocetData(val) {
      this.messageList = []
      // val = String.fromCharCode.apply(null, new Uint8Array(val)).trim() // 如果后端返回数据格式是其他的，可能需要转换一下，比如这个，应该是转Unicode编码
      let msgList = val

      msgList = msgList.slice(1)

      msgList = msgList.slice(0, msgList.length - 2)

      msgList = msgList.split('},')
      // console.log(msgList)
      for (let i = 0; i < msgList.length; i++) {
        const item = JSON.parse(msgList[ i ] + '}')

        this.messageList.push(item)

      }

    },
    // websocet函数抛错： 返回错误信息 用于用户提示
    getWebsocetError(err) {
      this.socketShow = err.isShow
      this.webtext = err.messge
      console.log('websocet函数抛错', this.socketShow)
    },
    // websocet函数成功进入： 监听连接状态，在失败的时候弹窗提示，具体需求看自身情况
    onErrorSucceed(val) {
      this.socketShow = val.isShow
      console.log('websocet函数成功进入', this.socketShow)
    },
    /**
     * 获取消息列表
     */
    async getMessageList() {

      const res = await getmessageList({ senderId: getUserInfo().id })

      setTimeout(() => {
        this.loading = false
        this.triggered = false
      }, 300)
      this.messageList = res.data
    },
    /** 刷新 */
    async refresh() {
      this.triggered = true
      this.getMessageList()
      setTimeout(() => {
        this.triggered = false
      }, 500)
    }
  },
  // 离开页面销毁websocket
  beforeDestroy() {
    websocetObj.stop()
  },
  destroy() {
    websocetObj.stop()
    console.log('12')

    clearInterval(this.inter)
    this.inter = null

  },
  onUnload() {
    console.log('2')
    if (this.inter) {
      clearInterval(this.inter)
      this.inter = null
    }
  },
  onHide() {

    console.log('3', this.inter)

    clearInterval(this.inter)
    inter = null

  },

}
</script>
<style lang="scss">
	.interact-message {
		background-color: #f5f5f5;
    overflow: hidden;
		width: 100wh;
    height: 98vh;
		overflow: hidden;
    text-align: center;
    .u-loadmore{
      padding-top: 150rpx;
    }
    .scroll-refresh{
      min-height: 90vh;
      padding-bottom: 60rpx;
    }
	}
</style>
